<?php

/**
 * Description of AclController
 *
 * @author gun
 */
require_once 'BaseController.php';
class Admin_AclController extends Admin_BaseController {
    
    public function init() {
        parent::init();
    }
    
    public function indexAction() {
        $request = $this->getRequest();

        if ($this->httpRequest()->isXmlHttpRequest()) {
            $q = $request->getParam('q');
            $page = $request->getParam('page');
            
            $where = (isset($q) ? array('name LIKE ?' => "%$q%") : array());
            $stat = $this->_helper->ListPage('Admin_Model_GroupService', $page, $where);
            
            $options = array(
                'limit'=>
                    array(
                        $stat['perpage'] => $stat['offset'])
            );
            
            $service = AppRegistry::loadService('Admin_Model_GroupService');
            $data = $service->getGroup($where, $options);
            
            if ($data) {
                $this->_helper->json(array(
                    'data' => $data,
                    'pview'=> $stat['pview'],
                    'offset'=> $stat['offset'],
                    'fieldname'=> 'description'
                    ));
                
            } else {
                $this->_helper->json(array('error'=>'No Data Found.'));
            }
        }
    }
    
    public function editAction() {
        $groupID = $this->getParam('id', null);
        
        $service = AppRegistry::loadService('Admin_Model_AclService');
        $data = $service->findRow($groupID);
        
        $this->view->data = $data;
    }
    
    public function saveAction() {        
        $this->getRequest()->clearParams();
        
        $id = $this->_getParam('groupid');              
        $data = $this->_getAllParams();
        unset($data['groupid']);
        
        $baseUserInfo = $this->baseUserLogin($id);

        try {
            $service = AppRegistry::loadService('Admin_Model_AclService');
            
            $temp = array();
            foreach($data as $key=>$value) {                    
                $mid = explode('_', $key);
                $menuID = $mid[1];

                $temp['status'] = ('true' === $value);

                foreach($baseUserInfo as $k => $v) $temp[ $k ] = $v;                       
                $where = array('groupID = ?' => $id, 'menuID = ?' => $menuID); //var_dump($temp);
                $save = $service->doUpdate($temp, $where);
            }            

            $this->_helper->json(array('status'=>($save ? 'Save Success.' : 'Nothing changed')));
        } catch (Exception $exc) {
            $this->_helper->json(array('status'=>$exc->getMessage()));            
        }
        
        $this->_helper->viewRenderer->setNoRender();
    }
}
